<?php
namespace app\api\controller\v1;

use app\common\controller\Api;
use app\common\model\Area;
use app\common\model\LitestoreShop;
use app\common\model\UserCollectShop;
use app\common\service\LitestoreNews as LitestoreNewsService;
use app\common\service\LitestoreShop as LitestoreShopService;
use app\common\service\LitestoreShopCategory as LitestoreShopCategoryService;
use think\Db;
use think\Request;


class App extends Api {
    protected $noNeedLogin = ['index','detail','lists','nearShop','collectShop','shopComment'];
    protected $noNeedRight = '*';

    public function index(){
        $areaModel=new Area();
        //商家表
        $LitestoreShopCategoryService = new LitestoreShopCategoryService();
        $LitestoreNewsService =  new LitestoreNewsService();
        $LitestoreShopService = new LitestoreShopService();
        $offset = $this->request->request('offset');
        $longitude= $this->request->request('longitude'); //经度114.03289881
        $latitude = $this->request->request('latitude'); //纬度 22.64382712
        $offsets = $offset?$offset:1;

        $x=0;//经度
        $y=0;//维度

        //经度
        if($latitude==0&&$latitude==0){
            if( cookie( 'cache_ip_location' )){
                if(!empty(cookie( 'cache_ip_location' )['content'])){
                    $point=cookie( 'cache_ip_location' )['content']['point'];
                    $x=$point['x'];
                    $y=$point['y'];
                }
            }
            if(cookie('cache_location_city')){
                $area=cookie('cache_location_city');
                $city=get_location_city($area['city']);
                $map['city'] = $city['id'];
            }
        }else{
            $x=trim($longitude);
            $y=trim($latitude);
            $cityList=getCityList($y.','.$x);
            if(!empty($cityList)){
                $city=Db::name('area')->where(['name'=>$cityList['city']])->find();
                $map['city'] = $city['id'];
            }
        }

        $order="weigh desc";
        $map['status'] = 1;
        $data['Shop'] = $LitestoreShopService->ShopByPosidList($map,$order,$offsets);

            foreach ($data['Shop'] as $key=>&$val){
                if(!empty($x)&&!empty($y)){
                    if(!empty($val['longitude'])&&!empty($val['latitude'])){
                        $val['length'] = web_getDistance($x,$y,$val['longitude'],$val['latitude']);
                    }else{
                        $val['length']=0;
                    }
                }else{
                    $val['length']=0;
                }
            }



        //商家分类
        $data['category'] = $LitestoreShopCategoryService->select('','id,name');
        $banner = ['status'=>'normal'];
        $data['banner'] = $LitestoreNewsService->select($banner,'id,title,image');
        if(!$data){
            return json(array('code'=>0,"data"=>[],'msg'=>"暂无产品展示"));
        }
        $this->success("请求成功",$data);
   }
    /**
     * 好店详情
     * id 商店id
     * 用户经纬度坐标
     * 评论 分页 默认 6条
     */
   public function detail(){
       $id = $this->request->request('id');
       $userinfo = $this->auth->getUser();
       $uid=(int)$userinfo['id'];
       if(!$id){
           $this->error('产品不存在');
       }
       $LitestoreShopService = new LitestoreShopService();
       $data = $LitestoreShopService->getComment($id,$uid);
        if(!$data){
            return json(array('code'=>0,"data"=>[],'msg'=>"暂无产品展示"));
        }
       $this->success("请求成功",$data[0]);
   }

    /**
     * 商店列表 分类 排序
     */
    public function lists(){
        $LitestoreShopService = new LitestoreShopService();
        $keysword = $this->request->request('keysword');
        $category_id = $this->request->request('category_id');

        $offset = $this->request->request('offset');
        $longitude= $this->request->request('longitude'); //经度114.03289881
        $latitude = $this->request->request('latitude'); //纬度 22.64382712
        $offsets = $offset?$offset:1;

        $x=0;//经度
        $y=0;//维度


        //经度
        if($latitude==0&&$latitude==0){
            if( cookie( 'cache_ip_location' )){
                if(!empty(cookie( 'cache_ip_location' )['content'])){
                    $point=cookie( 'cache_ip_location' )['content']['point'];
                    $x=$point['x'];
                    $y=$point['y'];
                }
            }
            if(cookie('cache_location_city')){
                $area=cookie('cache_location_city');
                $city=get_location_city($area['city']);
                $map['city'] = $city['id'];
            }
        }else{
            $x=trim($longitude);
            $y=trim($latitude);
            $cityList=getCityList($y.','.$x);
            if(!empty($cityList)){
                $city=Db::name('area')->where(['name'=>$cityList['city']])->find();
                $map['city'] = $city['id'];
            }
        }


//        $province = $this->request->request('province');
//        $city = $this->request->request('city');
//        $area = $this->request->request('area');
        $order="weigh desc";
//        if($this->request->request('res_point')=='res_point'){
//            $order.=',res_point desc';
//        }
        if($category_id){
            $map['category_id']=$category_id;
        }
        if($keysword){
            $map['name']=['like','%'.$keysword.'%'];
        }
//        if($province){
//            $map['province']=$province;
//        }
//        if($city){
//            $map['city']=$city;
//        }
//        if($area){
//            $map['area']=$area;
//        }

        $map['status'] =1;
        $offset = $this->request->request('offset');
        $offsets = $offset?$offset:0;
        $number = $this->request->request('limit');
        $limit = $number?$number:10;
//        $limits = $offsets.','.$limit;
        $data = $LitestoreShopService->getList($map,$order,$limit,$offsets);
        foreach ($data as $key=>&$val){
            if(!empty($x)&&!empty($y)){
                if(!empty($val['longitude'])&&!empty($val['latitude'])){
                    $val['length'] = web_getDistance($x,$y,$val['longitude'],$val['latitude']);
                }else{
                    $val['length']=0;
                }
            }else{
                $val['length']=0;
            }
        }
        if(!$data){
            return json(array('code'=>0,"data"=>[],'msg'=>"暂无产品展示"));
        }
        $this->success("请求成功",$data);
    }
    /**
     * 附近商家
     */
    public function nearShop(){

        $LitestoreShop = new LitestoreShop();
        $keysword = $this->request->request('keysword');
        $category_id = $this->request->request('category_id');
        $offset = $this->request->request('offset');


        if($category_id){
            $map['s.category_id']=$category_id;
        }
        if($keysword){
            $map['s.name']=['like','%'.$keysword.'%'];
        }

        $map['s.status'] ='1';

        $longitude= $this->request->request('longitude'); //经度114.03289881
        $latitude = $this->request->request('latitude'); //纬度 22.64382712


        $x=114.045094;//经度
        $y=22.646479;//维度

        //经度
        if($latitude==0&&$latitude==0){
            if(cookie( 'cache_ip_location' )){
                if(!empty(cookie( 'cache_ip_location' )['content'])){
                    $point=cookie( 'cache_ip_location' )['content']['point'];
                    $x=$point['x'];
                    $y=$point['y'];
                }
            }
        }else{
            $x=$longitude;
            $y=$latitude;
        }


        $field = 'average,id,name,shop_image,longitude,latitude,category_id,';
        $field .= '( 6371.137 * acos (cos(radians('.$y.'))*cos( radians( s.latitude ))*cos( radians(s.longitude )-radians('.$x.'))+sin(radians('.$y.'))*sin(radians(s.latitude)))) AS distance';
        $order="distance asc";

        $data = $LitestoreShop->getList($map,$order,$field,$offset);
        foreach ($data as $k=>$v){
            if(!empty($x)&&!empty($y)){
                if(!empty($val['longitude'])&&!empty($val['latitude'])){
                    @$data[$k]['length'] = web_getDistance($x,$y,$v['longitude'],$v['latitude']);
                }else{
                    @$data[$k]['length']=0;
                }
            }else{
                @$data[$k]['length']=0;
            }
            @$data[$k]['tag_list']=$v['get_shop_by_tag'];
        }


        if(!$data){
            return json(array('code'=>0,"data"=>[],'msg'=>"暂无产品展示"));
        }
        $this->success("请求成功",$data);


//        $LitestoreShopService = new LitestoreShopService();
//        $keysword = $this->request->request('keysword');
//        $province = $this->request->request('province');
//        $city = $this->request->request('city');
//        $area = $this->request->request('area');
//
////       37.8119075312,112.5691299892
////        103.81712,36.128204
//        $lat = 37.8119075312;
//        $lng = 112.5691299892;
//        $order="weigh desc";
//        if($this->request->request('res_point')=='res_point'){
//            $order.=',res_point desc';
//        }
//        $array = getAround($lat, $lng, config('area.around'));
//        $map['latitude']  = array(array('EGT',$array['minLat']),array('ELT',$array['maxLat']),'and');
//        $map['longitude'] = array(array('EGT',$array['minLng']),array('ELT',$array['maxLng']),'and');
//
//        if($keysword){
//            $map['name']=['like','%'.$keysword.'%'];
//        }
//        if($province){
//            $map['province']=$province;
//        }
//        if($city){
//            $map['city']=$city;
//        }
//        if($area){
//            $map['area']=$area;
//        }
////        $map = ['category_id'=>2,'status'=>1];
//        $offset = $this->request->request('offset');
//        $offsets = $offset?$offset:0;
//        $number = $this->request->request('limit');
//        $limit = $number?$number:6;
//        $limits = $offsets.','.$limit;
//        $data = $LitestoreShopService->getList($map,$order,$limits);


    }

    /**
     * @param $id
     * @param $type
     * 收藏/取消收藏店铺
     */
    public function collectShop()
    {
        $id= $this->request->request('id');
        $type= $this->request->request('type');
        $userinfo = $this->auth->getUser();
        $uid=(int)$userinfo['id'];
        $UserCollectShop = new UserCollectShop();
        $res = $UserCollectShop->collect_shop($uid,$id,$type);
        if($res == 1){
            $this->success('操作成功');
        }elseif($res == -1){
            $this->error('已添加不许重复添加');
        }elseif($res == -2){
            $this->error('不存在无法删除');
        }else{
            $this->error('操作失败，请重试');
        }
    }

    public function shopComment(){
        //评论列表
        $page = $this->request->request('offset',1);
        $map['s.id'] = $this->request->request('id',1);
        $list = db('litestore_shop')->alias('s')
            ->field('u.username,c.*')
            ->join('__LITESTORE_SHOPORDER__ o','o.litestore_shop_id = s.id')
            ->join('__LITESTORE_SHOPCOMMENT__ c','c.litestore_shoporder_id = o.shoporder_id')
            ->join('__USER__ u','u.id = o.playUser_id')
            ->where($map)
            ->page($page)
            ->limit(10)
            ->select();
        if(!empty($list)){
            $this->success('请求成功',$list);
        }else{
            $this->success('暂无数据',[]);
        }

    }



}